package com.wangwenjun.concurrency.chapter14.countdownlatch;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/*
  t1.join t2.join t3.join must hold thread's reference, especially in using thread pool
 */
public class UseCountDownLatch5 {

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch cdl = new CountDownLatch(10);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Random random = new Random();
        String show[] = new String[10];

        for (int i = 0; i < 10; i++) {
            int index = i;
            executorService.submit(()->{
                for (int j = 0; j <= 100; j++) {
                    try {
                        Thread.sleep(random.nextInt(100)+1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    show[index] = j + "%";
                    System.out.print("\r"+Arrays.toString(show));
                }
                cdl.countDown();
            });
        }

        cdl.await();

        System.out.print("\r游戏开始");
        executorService.shutdown();
    }
}
